/*
 * DIM-SUM操作系统
 *
 * Copyright (C) 2022 国科础石(重庆)软件有限公司
 *
 * 作者: Dong Peng <w-pengdong@kernelsoft.com>
 *
 * License terms: GNU General Public License (GPL) version 3
 *
 */

#ifndef __ASM_TLBFLUSH_H
#define __ASM_TLBFLUSH_H

#ifndef __ASSEMBLY__

#include <dim-sum/sched.h>
#include <dim-sum/cpumask.h>
#include <asm/cputype.h>
#include <asm/smp.h>

/*
 * Flush entire local TLB.  'sfence.vma' implicitly fences with the instruction
 * cache as well, so a 'fence.i' is not necessary.
 */
static inline void local_flush_tlb_all(void)
{
	__asm__ __volatile__ ("sfence.vma" : : : "memory");
}

/* Flush one page from local TLB */
static inline void local_flush_tlb_page(unsigned long addr)
{
	__asm__ __volatile__ ("sfence.vma %0" : : "r" (addr) : "memory");
}

#ifndef CONFIG_SMP

#define flush_tlb_all() local_flush_tlb_all()
#define flush_tlb_page(vma, addr) local_flush_tlb_page(addr)

static inline void flush_tlb_range(struct vma_desc *vma,
		unsigned long start, unsigned long end)
{
	local_flush_tlb_all();
}

#define flush_tlb_mm(mm) flush_tlb_all()

#else /* CONFIG_SMP */

#include <asm/sbi.h>

static inline void remote_sfence_vma(struct cpumask *cmask, unsigned long start,
				     unsigned long size)
{
	struct cpumask hmask;

	cpumask_clear(&hmask);
	riscv_cpuid_to_hartid_mask(cmask, &hmask);
	sbi_remote_sfence_vma(hmask.bits, start, size);
}

#define flush_tlb_all() local_flush_tlb_all()
#define flush_tlb_page(vma, addr) local_flush_tlb_page(addr)
#define flush_tlb_range(vma, start, end) \
	remote_sfence_vma(mm_cpumask((vma)->vm_mm), start, (end) - (start))
#define flush_tlb_mm(mm) \
	remote_sfence_vma(mm_cpumask(mm), 0, -1)

#endif /* CONFIG_SMP */

/* Flush a range of kernel pages */
static inline void flush_tlb_kernel_range(unsigned long start,
	unsigned long end)
{
	flush_tlb_all();
}


static inline void
flush_tlb_kernel_addr(unsigned long addr)
{
	flush_tlb_all();
}

static inline void
flush_tlb_addr(unsigned long asid_addr)
{
	flush_tlb_all();
}

#endif /* __ASSEMBLY__ */

#endif /* __ASM_TLBFLUSH_H */
